package cn.ratel.route;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class ActionParamProvider {

	private static Map<Class<?>, Injector> injectorMap = new HashMap<Class<?>, Injector>() {
		{
			for (ActionParamProvider.Injector injector : DefaultInjectors.values()) {
				put(getType(injector), injector);
			}
		}
	};

	private static Class<?> getType(ActionParamProvider.Injector injector) {
		Class<?> returnType;
		try {
			returnType = injector.getClass().getMethod("inject", HttpServletRequest.class, HttpServletResponse.class, String.class).getReturnType();
		} catch (NoSuchMethodException e) {
			throw new RuntimeException("invalid injector : " + injector.getClass().getName(), e);
		}
		return returnType;
	}

	private ActionParamProvider() {
	}

	static Injector getInjector(Class<?> clazz) {
		return injectorMap.get(clazz);
	}

	public interface Injector {
		Object inject(HttpServletRequest req, HttpServletResponse res, String paramName);
	}

	public static void addInjector(Class<?> injectClazz, Injector injector) {
		injectorMap.put(injectClazz, injector);
	}

}
